package main

import (
	"encoding/json"
	"fmt"
	"github.com/valyala/fasthttp"
	"log"
	"time"
)

var (
	url = "http://192.168.72.133:9200/"
)

/*
通过http的方式请求es
*/

func main() {
	var err error

	// 新增数据
	//err = ReqHttpCreateDataToEs()
	//if err != nil{
	//	log.Fatal("新增数据错误：", err)
	//}

	////查询数据
	//err = ReqHttpSearchDataFromEs()
	//if err != nil{
	//	log.Fatal("查询数据错误：", err)
	//}

	// 修改数据
	err = ReqHttpUpdateDataFromEs()
	if err != nil {
		log.Fatal("修改数据错误：", err)
	}

}

/*
新增数据
*/

type CreateResponseParam struct {
	ID          string `json:"_id"`
	Index       string `json:"_index"`
	PrimaryTerm int64  `json:"_primary_term"`
	SeqNo       int64  `json:"_seq_no"`
	Shards      struct {
		Failed     int64 `json:"failed"`
		Successful int64 `json:"successful"`
		Total      int64 `json:"total"`
	} `json:"_shards"`
	Type    string `json:"_type"`
	Version int64  `json:"_version"`
	Result  string `json:"result"`
}

type Book struct {
	BookAuthor string `json:"book_author"`
	BookCode   string `json:"book_code"`
	BookDesc   string `json:"book_desc"`
	BookID     int64  `json:"book_id"`
	BookName   string `json:"book_name"`
	BookPrice  int64  `json:"book_price"`
}

func ReqHttpCreateDataToEs() error {
	reqUrl := url + "local_library/book/"
	book := Book{"吴承恩", "A0005", "最好看的玄幻小说！", 8, "聊斋记", 320}
	req := &fasthttp.Request{}
	req.SetRequestURI(reqUrl)
	req.Header.SetContentType("application/json")
	req.Header.SetMethod("POST")
	requestBody := fmt.Sprintf(`{"book_author": "%s", "book_code": "%s",  "book_desc": "%s", "book_id":%d, "book_name": "%s", "book_price":%d }`,
		book.BookAuthor, book.BookCode, book.BookDesc, book.BookID, book.BookName, book.BookPrice)
	fmt.Println("Create请求参数为：", requestBody)
	req.SetBody([]byte(requestBody))
	resp := &fasthttp.Response{}
	cli := &fasthttp.Client{}
	if err := cli.DoTimeout(req, resp, time.Second*10); err != nil {
		return err
	}
	result := new(CreateResponseParam)
	err := json.Unmarshal(resp.Body(), result)
	if err != nil {
		return err
	}
	fmt.Println("新增数据结果为：", result)
	return nil
}

/*
查询数据
*/

type SearchQueryParam struct {
	Match struct {
		BookCode string `json:"book_code"`
	} `json:"match"`
}

type SearchRespParam struct {
	Shards struct {
		Failed     int64 `json:"failed"`
		Skipped    int64 `json:"skipped"`
		Successful int64 `json:"successful"`
		Total      int64 `json:"total"`
	} `json:"_shards"`
	Hits struct {
		Hits []struct {
			ID     string  `json:"_id"`
			Index  string  `json:"_index"`
			Score  float64 `json:"_score"`
			Source struct {
				BookAuthor string `json:"book_author"`
				BookCode   string `json:"book_code"`
				BookDesc   string `json:"book_desc"`
				BookID     int64  `json:"book_id"`
				BookName   string `json:"book_name"`
				BookPrice  int64  `json:"book_price"`
			} `json:"_source"`
			Type string `json:"_type"`
		} `json:"hits"`
		MaxScore float64 `json:"max_score"`
		Total    int64   `json:"total"`
	} `json:"hits"`
	TimedOut bool  `json:"timed_out"`
	Took     int64 `json:"took"`
}

func ReqHttpSearchDataFromEs() error {
	reqUrl := url + "local_library/_search?pretty"
	query := new(SearchQueryParam)
	query.Match.BookCode = "A0005"
	queryStr, err := json.Marshal(query)
	if err != nil {
		log.Println("json.Marshal(query) err:", err)
		return err
	}
	req := &fasthttp.Request{}
	req.SetRequestURI(reqUrl)
	req.Header.SetContentType("application/json")
	req.Header.SetMethod("POST")
	requestBody := fmt.Sprintf(`{"query": %s}`, queryStr)
	fmt.Println("search请求参数为：", requestBody)
	req.SetBody([]byte(requestBody))
	resp := &fasthttp.Response{}
	cli := &fasthttp.Client{}
	if err := cli.DoTimeout(req, resp, time.Second*10); err != nil {
		return err
	}
	result := new(SearchRespParam)
	err = json.Unmarshal(resp.Body(), result)
	if err != nil {
		return err
	}
	fmt.Println("查询数据结果为：", result.Hits.Hits)
	return nil
}

func ReqHttpUpdateDataFromEs() error {
	reqUrl := url + "local_library/book/"
	book := Book{"吴承恩", "A0005", "最好看的玄幻小说！", 9, "聊斋记", 320}
	req := &fasthttp.Request{}
	req.SetRequestURI(reqUrl)
	req.Header.SetContentType("application/json")
	req.Header.SetMethod("POST")
	requestBody := fmt.Sprintf(`{"book_author": "%s", "book_code": "%s",  "book_desc": "%s", "book_id":%d, "book_name": "%s", "book_price":%d }`,
		book.BookAuthor, book.BookCode, book.BookDesc, book.BookID, book.BookName, book.BookPrice)
	fmt.Println("update请求参数为：", requestBody)
	req.SetBody([]byte(requestBody))
	resp := &fasthttp.Response{}
	cli := &fasthttp.Client{}
	if err := cli.DoTimeout(req, resp, time.Second*10); err != nil {
		return err
	}
	result := new(CreateResponseParam)
	err := json.Unmarshal(resp.Body(), result)
	if err != nil {
		return err
	}
	fmt.Println("update数据结果为：", result)
	return nil
}

/*
修改数据
*/

/*
删除数据
*/
